//作者：黄萌
var express = require('express');
var router = express.Router();
var db = require("../model/db");
var multer =require("multer")
var path =require("path")
//添加门店
router.post("/", async (req, res) => {
    const data = await db.Shop.create(req.body);
    res.send({
        code: 0,
        message: "",
        data,
        count: ""
    });
})
//添加门店职员
router.put("/clerk/:id", async (req, res) => {
    const u = await db.Shop.findById(req.params.id);
    u.clerk.push(req.body);
    await db.Shop.updateOne({ _id: req.params.id }, u);
    const data = await db.Shop.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    });
})
// 删除门店内单个职员
router.put("/staff/:id", async (req, res) => {
    let data = await db.Shop.findById(req.params.id);
    data.clerk = data.clerk.filter(it => it._id != req.body.clerkId);
    const a = await db.Shop.updateOne({ _id: req.params.id }, data)
    res.send({
        code: 0,
        message: "",
        data: a
    });
})
//删除门店
router.delete("/:id", async (req, res) => {
    const data = await db.Shop.deleteOne({
        _id: req.params.id
    });
    res.send({
        code: 0,
        message: "",
        data
    });
})
//查询门店内单个职员
router.get("/staff", async (req, res) => {
    let data = await db.Shop.findById(req.query.sid);
    data = data.clerk.filter(it => it._id == req.query.cid)
    res.send({
        code: 0,
        message: "",
        data: data
    });
})
//查询门店
router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //分页
    if (!req.query.page) {
        req.query.page = 1;
    }
    if (!req.query.limit) {
        req.query.limit = 5;
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i");
        condition = {
            $or: [
                { shopName: { $regex: exp } },
            ]
        };
    }
    const data = await db.Shop.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    const count = await db.Shop.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        data,
        count
    });
})
//查询单个门店
router.get("/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    });
})
//修改门店
router.put("/:id", async (req, res) => {
    const data = await db.Shop.updateOne({
        _id: req.params.id
    }, req.body)
    res.send({
        code: 0,
        message: "",
        data
    });
})
//查询门店内全部职员
router.get("/clerk/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data: data.clerk
    });
})

//添加门店商品种类
router.post("/goods", async (req, res) => {

    const data = await db.Shop.findById(req.query.id);
    const by = data.goods.filter(it => it == req.query.goods);
    if (by.length > 0) {
        res.send({
            "code": 0,
            "message": "该门店，已经有该商品",
            data: false
        })
    } else {
        data.goods = data.goods.push(req.query.goods);
        data.amount = data.amount.push({
            id: req.query.goods,//商品编号
            num: 0//商品数量
        })
        await db.Shop.updateOne({//条件对象
            _id: data._id,
        }, data)
        res.send({
            "code": 0,
            "message": "",
            data
        })
    }
})

//获取总销售量  id:门店id 
router.get("/totalSales/:id", async (req, res) => {
    let num = 0;
    const data = await db.Shop.findById(req.params.id);
    for (let i = 0; i < data.amount.length; i++) {
        num += data.amount[i].num;
    }
    res.send({
        "code": 0,
        "message": "",
        data: num
    })
})

//查看所有销售
router.get("/sale/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id);
    res.send({
        "code": 0,
        "message": "",
        data: data.amount
    })
})

router.get("/goods/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id).populate("goods");
    res.send({
        code: 0,
        message: "",
        data: data.goods
    });
})

// 删除门店内单个商品
router.put("/deletegoods/:id", async (req, res) => {
    let data = await db.Shop.findById(req.params.id);
    data.goods = data.goods.filter(it => it._id != req.body.goodId);
    data.amount = data.amount.filter(it => it.id != req.body.goodId);
    const a = await db.Shop.updateOne({ _id: req.params.id }, data)
    res.send({
        code: 0,
        message: "",
        data: a
    });
})

  
//添加门店服務种类
router.post("/services", async (req, res) => {
    const data = await db.Shop.findById(req.query.id);
    const by = data.services.filter(it => it == req.query.services);
    if (by.length > 0) {
        res.send({
            "code": 0,
            "message": "该门店，已经有该服務",
            data: false
        })
    } else {
        data.services = data.services.push(req.query.services);
        await db.Shop.updateOne({//条件对象
            _id: data._id,
        }, data)
        res.send({
            "code": 0,
            "message": "",
            data
        })
    }
})
router.get("/services/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id).populate("services");
    res.send({
        code: 0,
        message: "",
        data: data.services
    });
})

//得到商店内商品的销售

//作者：黄萌
var express = require('express');
var router = express.Router();
var db = require("../model/db");

//添加门店
router.post("/", async (req, res) => {
    const data = await db.Shop.create(req.body);
    res.send({
        code: 0,
        message: "",
        data,
        count: ""
    });
})
//添加门店职员
router.put("/clerk/:id", async (req, res) => {
    const u = await db.Shop.findById(req.params.id);
    u.clerk.push(req.body);
    await db.Shop.updateOne({ _id: req.params.id }, u);
    const data = await db.Shop.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    });
})
// 删除门店内单个职员
router.put("/staff/:id", async (req, res) => {
    let data = await db.Shop.findById(req.params.id);
    data.clerk = data.clerk.filter(it => it._id != req.body.clerkId);
    const a = await db.Shop.updateOne({ _id: req.params.id }, data)
    res.send({
        code: 0,
        message: "",
        data: a
    });
})
//删除门店
router.delete("/:id", async (req, res) => {
    const data = await db.Shop.deleteOne({
        _id: req.params.id
    });
    res.send({
        code: 0,
        message: "",
        data
    });
})
//查询门店内单个职员
router.get("/staff", async (req, res) => {
    let data = await db.Shop.findById(req.query.sid);
    data = data.clerk.filter(it => it._id == req.query.cid)
    res.send({
        code: 0,
        message: "",
        data: data
    });
})
//查询门店
router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //分页
    if (!req.query.page) {
        req.query.page = 1;
    }
    if (!req.query.limit) {
        req.query.limit = 5;
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i");
        condition = {
            $or: [
                { shopName: { $regex: exp } },
            ]
        };
    }
    const data = await db.Shop.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    const count = await db.Shop.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        data,
        count
    });
})
//查询单个门店
router.get("/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    });
})
//修改门店
router.put("/:id", async (req, res) => {
    const data = await db.Shop.updateOne({
        _id: req.params.id
    }, req.body)
    res.send({
        code: 0,
        message: "",
        data
    });
})
//查询门店内全部职员
router.get("/clerk/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data: data.clerk
    });
})

//添加门店商品种类
router.post("/goods", async (req, res) => {

    const data = await db.Shop.findById(req.query.id);
    const by = data.goods.filter(it => it == req.query.goods);
    if (by.length > 0) {
        res.send({
            "code": 0,
            "message": "该门店，已经有该商品",
            data: false
        })
    } else {
        data.goods = data.goods.push(req.query.goods);
        data.amount = data.amount.push({
            id: req.query.goods,//商品编号
            num: 0//商品数量
        })
        await db.Shop.updateOne({//条件对象
            _id: data._id,
        }, data)
        res.send({
            "code": 0,
            "message": "",
            data
        })
    }
})

//获取总销售量  id:门店id 
router.get("/totalSales/:id", async (req, res) => {
    let num = 0;
    const data = await db.Shop.findById(req.params.id);
    for (let i = 0; i < data.amount.length; i++) {
        num += data.amount[i].num;
    }
    res.send({
        "code": 0,
        "message": "",
        data: num
    })
})

//查看所有销售
router.get("/sale/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id);
    res.send({
        "code": 0,
        "message": "",
        data: data.amount
    })
})

router.get("/goods/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id).populate("goods");
    res.send({
        code: 0,
        message: "",
        data: data.goods
    });
})

// 删除门店内单个商品
router.put("/deletegoods/:id", async (req, res) => {
    let data = await db.Shop.findById(req.params.id);
    data.goods = data.goods.filter(it => it._id != req.body.goodId);
    data.amount = data.amount.filter(it => it.id != req.body.goodId);
    const a = await db.Shop.updateOne({ _id: req.params.id }, data)
    res.send({
        code: 0,
        message: "",
        data: a
    });
})

  
//添加门店服務种类
router.post("/services", async (req, res) => {
    const data = await db.Shop.findById(req.query.id);
    const by = data.services.filter(it => it == req.query.services);
    if (by.length > 0) {
        res.send({
            "code": 0,
            "message": "该门店，已经有该服務",
            data: false
        })
    } else {
        data.services = data.services.push(req.query.services);
        await db.Shop.updateOne({//条件对象
            _id: data._id,
        }, data)
        res.send({
            "code": 0,
            "message": "",
            data
        })
    }
})
router.get("/services/:id", async (req, res) => {
    const data = await db.Shop.findById(req.params.id).populate("services");
    res.send({
        code: 0,
        message: "",
        data: data.services
    });
})

//得到商店内商品的销售
// 随机函数 方便命名文件
function rand(min, max) {
    const dec = max - min;
    return parseInt(Math.random() * dec + min);
}

//作者:lh
// 创建存储对象
const storage = multer.diskStorage({ //文件名
    destination: path.join(__dirname, "../public/upload/"), //配置文件存储的目标文件夹
    filename: function (req, file, cb) { //配置文件名
        const fname = Date.now() + "" + rand(1000000, 10000000) + path.extname(file.originalname).toLowerCase();
        cb(null, fname);
    }
});

// 作者：lh
//配置上传处理
const upload = multer({
    storage,
    // 服务端如何限制文件类型
    fileFilter: function (req, file, cb) { //限制文件类型
        cb(null, true); //表示通过
    }
}).array("file");

// 作者：lh
// 请求方法
router.post("/upload/add", async (req, res) => {
    // 服务器如何响应错误
    upload(req, res, async function (err) { //文件类型不正确时不错误不出现到服务器
        
        if (err) {
            console.log("错误", err)
            res.send({
                code: 401,
                message: "",
                data: []
            })
        } else {
            // console.log("图片上传成功");
            const data = req.files.map(item => "http://localhost:3000/upload/" + item.filename);
            res.send({
                code: 0,
                message: "",
                data: data
            })
        }
    });
})


router.put("/upload/:id", async (req, res) => {
    upload(req, res, async function (err) { //文件类型不正确时不错误不出现到服务器
        if (err) {

        } else {
            await db.Supplier.updateOne({
                _id: db.ObjectId(req.params.id)
            }, req.body); //(要修改的对象)
            res.send(true);
        }
    })
})


module.exports = router;
